package com.javadude.gcm1;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {
	private static final String SENDER_ID = "646771345062";
		// from the Google APIs project number
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
		  GCMRegistrar.register(this, SENDER_ID);
		} else {
		  Log.v("MainActivity", "Already registered");
		}
		
		// need to tell our server about the id
		new AsyncTask<Void, Void, String>() {
			protected void onPreExecute() {
				((TextView)findViewById(R.id.text)).setText("Registering");
			}
			@Override protected String doInBackground(Void... p) {
				try {
					HttpClient client = new DefaultHttpClient();  
					String postURL = "http://192.168.1.1:8080/com.javadude.gcm.server/ManagerServlet";
					HttpPost post = new HttpPost(postURL); 
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("regId", regId));
					params.add(new BasicNameValuePair("action", "register"));
					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);
					String status = responsePOST.getStatusLine().toString();
					Log.i("RESPONSE", status);
					return status;
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
			@Override protected void onPostExecute(String result) {
				((TextView)findViewById(R.id.text)).setText(result);
			}
		}.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
